/**
 * Title:
 * Description:
 * @author jjtEatJava
 * @date 2017年7月29日
 */
package com.leinao.logic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.leinao.bean.Field;
import com.leinao.config.JDBCConfig;

/**
 * Title:数据库类型与java类型的相互映射bean
 * Description:
 * @author wangshoufa
 * @date 2019年03月08日
 */

public class SimpleDao {
	private JDBCConfig jdbcConfig;

	public SimpleDao(JDBCConfig config) {
		this.jdbcConfig = config;
		if(config==null)
			throw new IllegalArgumentException("jdbcConfig 为 null");
		//加载驱动
		try {
			Class.forName(jdbcConfig.getDriver());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			throw new IllegalArgumentException("驱动："+jdbcConfig.getDriver()+" 不存在");
		}
	}

	/**
	 * 
	 * Title:获取全部表名
	 * Description:
	 * @return
	 * @throws SQLException
	 * @author jjtEatJava
	 * @date 2017年8月8日
	 */
	public  List<String> getAllTableName() throws SQLException {
		String sql = "show tables;";
		Connection conn = DriverManager.getConnection(jdbcConfig.getUrl(), jdbcConfig.getUsername(), jdbcConfig.getPassword());
		Statement statement = conn.createStatement();
		ResultSet set = statement.executeQuery(sql);
		List<String> list = new ArrayList<String>();
		while (set.next()) {
			String name = set.getString(1);
			list.add(name);
		}
		statement.close();
		conn.close();
		return list;
	}


	/**
	 * 
	 * Title:根据表名获取所有字段
	 * Description:
	 * @param tableName 表名
	 * @return
	 * @throws SQLException
	 * @author jjtEatJava
	 * @date 2017年8月8日
	 */
	public  List<Field> getAllFieldsByTableName(String tableName) throws SQLException {
		String sql = "desc " + tableName + ";";
		Connection conn = DriverManager.getConnection(jdbcConfig.getUrl(), jdbcConfig.getUsername(), jdbcConfig.getPassword());
		Statement statement = conn.createStatement();
		ResultSet set = statement.executeQuery(sql);
		List<Field> list = new ArrayList<Field>();
		while (set.next()) {
			String fieldName = set.getString("Field");
			String type = set.getString("Type");
			String key = set.getString("Key");
			Field field = new Field();
			field.setTableField(fieldName);
			field.setTableType(type);
			field.setTableKey(key);
			list.add(field);
		}
		statement.close();
		conn.close();
		return list;
	}
}
